package com.cssy.xxkj.logic.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.dao.LogicProductionStorageoutDAO;
import com.cssy.xxkj.logic.dao.LogicReceptDAO;
import com.cssy.xxkj.logic.dao.LogicReceptItemDAO;
import com.cssy.xxkj.logic.dao.LogicSalesDAO;
import com.cssy.xxkj.logic.entity.LogicProductionStorageoutDO;
import com.cssy.xxkj.logic.entity.LogicReceptDO;
import com.cssy.xxkj.logic.entity.LogicReceptItemDO;
import com.cssy.xxkj.logic.entity.LogicSalesDO;
import com.cssy.xxkj.logic.service.ILogicReceptService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicReceptService")
public class LogicReceptServiceImpl implements ILogicReceptService {

	@Resource(name = "logicReceptDAO")
	private LogicReceptDAO logicReceptDAO;
	
	@Resource(name = "logicReceptItemDAO")
	private LogicReceptItemDAO logicReceptItemDAO;
	
	@Resource(name = "logicSalesDAO")
	private LogicSalesDAO logicSalesDAO;
	
	@Resource(name = "logicProductionStorageoutDAO")
	private LogicProductionStorageoutDAO logicProductionStorageoutDAO;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicReceptDO>  list = logicReceptDAO.find(scs);
		rs.setRecordCount(logicReceptDAO.count(scs));
		rs.setResults(list);
		return rs;
	}
	
	@Override
	public List<LogicReceptItemDO> findItemListByMap(Map<String, Object> paramMap)
			throws SyBaseException {
		return logicReceptItemDAO.findListByMap(paramMap);
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		return logicReceptDAO.deleteLogicReceptDOByPrimaryKey(id);
	}

	@Override
	public Integer update(LogicReceptDO t, User user) throws SyBaseException {
		t.setBizModifyName(user.getName());
		t.setBizModifyDate(new Date());
		t.setBizVersionMark(t.getBizVersion());
		t.setBizVersion(t.getBizVersion()+1);
		return logicReceptDAO.updateLogicReceptDO(t);
	}

	@Override
	public LogicReceptDO save(LogicReceptDO curAP, User user)
			throws SyBaseException {
		curAP.setBizCreatorName(user.getName());
		curAP.setBizCreatorDate(new Date());
		curAP.setBizVersion(Integer.valueOf(1));
		logicReceptDAO.insertLogicReceptDO(curAP);
		return curAP;
	}
	
	@Override
	public LogicReceptDO findListById(String id) throws SyBaseException {
		return logicReceptDAO.findLogicReceptDOByPrimaryKey(id);
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		return logicReceptDAO.deleteBizRemoved(id);
	}
	
	@Override
	public void receptSave(LogicReceptDO curAP, HttpServletRequest request)
			throws SyBaseException{
		String dataitem = request.getParameter("dataitem");
		String detadele = request.getParameter("datadele");
		String zd014ReptDate = request.getParameter("zd014ReptDate");
		if(StringUtils.isNotBlank(zd014ReptDate)){
			curAP.setZd014ReptDate(DateUtils.stringToDate(zd014ReptDate));
		}else{
			curAP.setZd014ReptDate(new Date());
		}
		try{
			String reptId = "";
			String reptCode = "";
			//默认是未收款
			curAP.setZd003ReptStatus(BillStatusUtil.REP_MONEEY_BILL_STATUS_ONE);
			if(curAP==null || StringUtils.isBlank(curAP.getId())){
				//新增
				reptId = IDCodeTypeUtil.getId();
				curAP.setId(reptId);
				reptCode = syCodeService.getCode(BillTypeConstant.RECEPTPAY,
						BillTypeConstant.RECEPTPAY, SyCode.DATE_YYMM, 5);
				curAP.setZd001ReptCode(reptCode);
				this.save(curAP, SessionUtil.getUser(request));
			}else{
				//修改
				Integer row = this.update(curAP, SessionUtil.getUser(request));
				if(row==null || row.intValue()==0){
					throw new SyBaseException("数据发生改变，请重新提交！");
				}else{
					if(StringUtils.isNotBlank(detadele)){
						List<LogicReceptItemDO> reptItemList = JSONArray.parseArray(detadele, LogicReceptItemDO.class);
						for(LogicReceptItemDO reptItem : reptItemList){
							if(reptItem==null || StringUtils.isBlank(reptItem.getId())){
								continue;
							}
							logicReceptItemDAO.updateLogicReceptItemDO(reptItem);
						}
					}
				}
			}
			//新增、修改行记录信息修改
			List<LogicReceptItemDO> reptItemList = JSONArray.parseArray(dataitem, LogicReceptItemDO.class);
			for(LogicReceptItemDO reptItem : reptItemList){
				if(reptItem==null){
					continue;
				}
				if(StringUtils.isBlank(reptItem.getId())){
					reptItem.setId(IDCodeTypeUtil.getId());
					reptItem.setZd001ReptId(reptId);
					reptItem.setZd001ReptCode(reptCode);
					logicReceptItemDAO.insertLogicReceptItemDO(reptItem);
				}else{
					logicReceptItemDAO.updateLogicReceptItemDO(reptItem);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
	}
	
	@Override
	public void receptCommit(LogicReceptDO curAP, HttpServletRequest request)
			throws SyBaseException{
		try{
			String dataitem = request.getParameter("dataitem");
			String detadele = request.getParameter("datadele");
			String zd014ReptDate = request.getParameter("zd014ReptDate");
			if(StringUtils.isNotBlank(zd014ReptDate)){
				curAP.setZd014ReptDate(DateUtils.stringToDate(zd014ReptDate));
			}else{
				curAP.setZd014ReptDate(new Date());
			}
			//未提交的收款(删除的付款单)
			if(StringUtils.isNotBlank(detadele)){
				List<LogicReceptItemDO> reptItemList = JSONArray.parseArray(detadele, LogicReceptItemDO.class);
				for(LogicReceptItemDO reptItem : reptItemList){
					if(reptItem==null || StringUtils.isBlank(reptItem.getId())){
						continue;
					}
					logicReceptItemDAO.deleteLogicReceptItemDOByPrimaryKey(reptItem.getId());
				}
			}
			
			
			//提交的收款
			BigDecimal zdThSum = BigDecimal.ZERO;//本次实付合计
			List<LogicReceptItemDO> receptItemList = JSONArray.parseArray(dataitem, LogicReceptItemDO.class);
			for(LogicReceptItemDO receptItem : receptItemList){
				if(receptItem == null){
					continue;
				}
				//已收总金额
				BigDecimal zdHsMoney = receptItem.getZd017HasMoney()==null?BigDecimal.ZERO:receptItem.getZd017HasMoney();
				//本次收款金额
				BigDecimal zdThMoney = receptItem.getZd018TheMoney()==null?BigDecimal.ZERO:receptItem.getZd018TheMoney();
				//未收金额
				BigDecimal zdNoMoney = receptItem.getZd019NoMoney()==null?BigDecimal.ZERO:receptItem.getZd019NoMoney();
				//修改已收金额
				receptItem.setZd017HasMoney(zdHsMoney.add(zdThMoney));
				//修改未收金额
				receptItem.setZd019NoMoney(zdNoMoney.subtract(zdThMoney));
				zdThSum = zdThSum.add(zdThMoney);
			}
			
			//修改销售订单的付款状态
			LogicSalesDO lgs = this.findSaleEntity(curAP.getZd002SaleId());
			if(lgs==null){
				throw new SyBaseException("查询不到对应的销售订单，请重新提交。");
			}
			//最后一次已付款
			BigDecimal lastSumMoney = this.findLastReceptHasMoney(curAP.getZd002SaleId());
			//应付总金额
			BigDecimal hasSumMoney = curAP.getZd004SumAmount();
			//剩余未付款金额
			BigDecimal surpSumMoney = hasSumMoney.subtract(lastSumMoney);
			//判断是否可以提交(未付款金额-本次付款总金额)
			BigDecimal jugeSumMoney = surpSumMoney.subtract(zdThSum);
			if(BigDecimal.ZERO.compareTo(jugeSumMoney)==0){
				//如果为零,则表示完全付款
				curAP.setZd003ReptStatus(BillStatusUtil.REP_MONEEY_BILL_STATUS_THREE);
				lgs.setZd027RepStatus(BillStatusUtil.SES_MONEEY_BILL_STATUS_THREE);
			}
			if(BigDecimal.ZERO.compareTo(jugeSumMoney)==1){
				//表示本次付款金额大于未付款金额
				throw new SyBaseException("您本次付款大于付款单历史未付款！");
			}
			if(BigDecimal.ZERO.compareTo(jugeSumMoney)==-1){
				//表示本次付款总额少于未付款总额
				curAP.setZd003ReptStatus(BillStatusUtil.REP_MONEEY_BILL_STATUS_TWO);
				lgs.setZd027RepStatus(BillStatusUtil.SES_MONEEY_BILL_STATUS_TWO);
			}
			logicSalesDAO.updateLogicSalesDO(lgs);
			//修改当前的付款记录
			curAP.setZd005HasAmount(lastSumMoney.add(zdThSum));
			curAP.setZd006NoAmount(hasSumMoney.subtract(lastSumMoney.add(zdThSum)));
			this.update(curAP, SessionUtil.getUser(request));
			//修改行记录信息
			for(LogicReceptItemDO recpItem : receptItemList){
				if(recpItem == null || StringUtils.isBlank(recpItem.getId())){
					continue;
				}
				logicReceptItemDAO.updateLogicReceptItemDO(recpItem);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
	}
	
	/**
	 * 查询最近一次收款的金额
	 * @param prodoutId
	 * @return 
	 */
	public BigDecimal findLastReceptHasMoney(String prodoutId)throws SyBaseException{
		try{
			SearchConditions receptScs = new SearchConditions();
			receptScs.setRemovedProperty(null);
			receptScs.addCondition("zd002SaleId", prodoutId, SearchCondition.OP_EQUAL);
			receptScs.setOrderBy("bizCreatorDate desc");
			List<LogicReceptDO> repcetList = logicReceptDAO.find(receptScs);
			if(repcetList==null || repcetList.isEmpty() || repcetList.size()==0){
				return BigDecimal.ZERO;
			}else{
				return repcetList.get(0).getZd005HasAmount();
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
	}
	
	private LogicSalesDO findSaleEntity(String prodoutId){
		LogicProductionStorageoutDO prdSg = logicProductionStorageoutDAO.findLogicProductionStorageoutDOByPrimaryKey(prodoutId);
		if(prdSg==null){
			return null;
		}else{
			SearchConditions gsScs = new SearchConditions();
			gsScs.setRemovedProperty(null);
			gsScs.addCondition("zd001FormCode", prdSg.getZd002OriCode(), SearchCondition.OP_EQUAL);
			List<LogicSalesDO> gcsList = logicSalesDAO.find(gsScs);
			if(gcsList==null||gcsList.isEmpty()||gcsList.size()==0){
				return null;
			}else{
				return gcsList.get(0);
			}
		}
	}
}
 